<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 1. 注意提示 -->
      <el-alert type="warning" title="注意: 只允许为第三级分类设置参数!" show-icon :closable="false"> </el-alert>
      <!-- 2. 选择分类 -->
      <el-row type="flex" :gutter="10" align="middle">
        <el-col :span="2.5">选择商品分类:</el-col>
        <el-col :span="7">
          <el-cascader :options="cateList" clearable :props="cascaderProps" v-model="selectedKeys" @change="cateChanged"></el-cascader>
        </el-col>
      </el-row>
      <!-- 3. 动态参数/静态属性 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的标签页 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="showAddParams">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTabList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleClose(i, scope.row)">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditParamDialog(scope.row.attr_id)"> 编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的标签页 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="showAddParams">添加属性</el-button>
          <!-- 静态参数表格 -->
          <el-table :data="onlyTabList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleClose(i, scope.row)">{{ item }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- 编辑按钮 -->
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditParamDialog(scope.row.attr_id)">编辑</el-button>
                <!-- 删除按钮 -->
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addParamsDialogVisible" width="50%" @close="addParamsDialogClosed">
      <!-- 对话框: 内容主题区 -->
      <el-form ref="addParamsFormRef" :model="addParams" :rules="addParamsRules" label-width="80px" label-position="right">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParams.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddParamsForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改参数的对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editParamsDialogVisible" width="50%" @close="editParamsDialogClosed">
      <!-- 对话框: 内容主题区 -->
      <el-form ref="editParamsFormRef" :model="editParams" :rules="addParamsRules" label-width="80px" label-position="right">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParams.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 对话框: 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditParamsForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 全部商品分类列表
      cateList: [],
      // 联机选择器配置
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
        // 选择任意一级
        // checkStrictly: true
      },
      // 选中的分类的id数组
      selectedKeys: [],
      // 标签页双向绑定
      activeName: 'many',
      // 动态参数的数据
      manyTabList: [],
      // 静态参数的数据
      onlyTabList: [],
      // 控制"添加参数"对话框的显示
      addParamsDialogVisible: false,
      // "添加参数"表单数据
      addParams: {},
      addParamsRules: {
        attr_name: [
          { required: true, message: '参数不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 15,
            message: '长度在 2 到 15 个字符',
            trigger: 'blur'
          },
          { whitespace: true, message: '不能为空格', trigger: 'blur' }
        ]
      },
      titleText: '动态参数',
      // "编辑参数"对话框的显示
      editParamsDialogVisible: false,
      // "编辑参数"表单数据对象
      editParams: {}
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res.data)
      this.cateList = res.data
    },
    // 级联选择框选中节点变化时触发
    cateChanged() {
      this.manyTabList = []
      this.onlyTabList = []
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        return
      }
      this.getParamsData()
    },
    // 根据当前分类id获取获取参数列表
    async getParamsData() {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log(res)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制按钮与文本框的切换显示
        item.inputVisible = false
        // 文本框输入内容
        item.inputValue = ''
        item.dynamicTags = item.attr_vals
      })
      if (this.activeName === 'many') {
        this.manyTabList = res.data
      } else {
        this.onlyTabList = res.data
      }
    },
    // 监听标签页点击事件
    handleTabClick() {
      this.getParamsData()
    },
    // 监听"添加参数"对话框关闭事件
    addParamsDialogClosed() {
      this.$refs.addParamsFormRef.resetFields()
      this.addParams = {}
    },
    // 显示"添加参数"对话框
    showAddParams() {
      this.addParams.attr_sel = this.activeName
      this.addParamsDialogVisible = true
    },
    // 提交"添加参数"表单
    submitAddParamsForm() {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, this.addParams)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    // 删除当前参数
    async deleteParam(param) {
      const result = await this.$messageBox
        .confirm('此操作将删除参数: ' + param.attr_name + ', 是否继续?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        })
        .catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/` + param.attr_id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    // 监听"编辑参数"对话框的关闭
    editParamsDialogClosed() {
      console.log('editclosed')
      this.$refs.editParamsFormRef.resetFields()
    },
    // 显示"编辑参数"对话框
    async showEditParamDialog(attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParams = res.data
      this.editParamsDialogVisible = true
    },
    // 提交"编辑参数"表单数据
    submitEditParamsForm() {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(`categories/${this.editParams.cat_id}/attributes/${this.editParams.attr_id}`, {
          attr_name: this.editParams.attr_name,
          attr_sel: this.editParams.attr_sel,
          attr_vals: this.editParams.attr_vals
        })
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    async handleClose(i, param) {
      param.dynamicTags.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${param.cat_id}/attributes/${param.attr_id}`, {
        attr_name: param.attr_name,
        attr_sel: param.attr_sel,
        attr_vals: param.dynamicTags.join(' ')
      })
      if (res.meta.status !== 200) {
        param.dynamicTags = param.attr_vals
        return this.$message.error(res.meta.msg)
      }
      param.attr_vals = param.dynamicTags
    },
    showInput(param) {
      param.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm(param) {
      if (param.inputValue.trim().length === 0) {
        param.inputValue = ''
        param.inputVisible = false
        return
      }
      const inputValue = param.inputValue.trim()
      param.dynamicTags.push(inputValue)
      const { data: res } = await this.$http.put(`categories/${param.cat_id}/attributes/${param.attr_id}`, {
        attr_name: param.attr_name,
        attr_sel: param.attr_sel,
        attr_vals: param.dynamicTags.join(' ')
      })
      if (res.meta.status !== 200) {
        param.dynamicTags = param.attr_vals
        return this.$message.error(res.meta.msg)
      }
      param.inputValue = ''
      param.inputVisible = false
      param.attr_vals = param.dynamicTags
    }
  },
  // 计算属性
  computed: {
    isDisabled() {
      return this.selectedKeys.length !== 3
    },
    // 当前选择的三级分类id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    }
  },
  watch: {
    activeName(newVal) {
      if (newVal === 'many') {
        this.titleText = '动态参数'
      } else {
        this.titleText = '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.input-new-tag {
  width: 120px;
}
</style>
